<template>
  <div class="el_btn_report">
      <div style="margin-bottom:3px;width:100%;float:left;">
        <el-button-group class="data">
          <el-button size="small" v-for="(btn,index) in btngroups.databtns" :key="btn.id" @click="doSearch(index,btn.type)" :class="btngroups.dataIndex==index?'active':''">{{btn.name}}</el-button>
          <!-- <el-button size="small" p="data" data-value="100" class="datadiy">自定义</el-button> -->
        </el-button-group>

        <el-button-group class="dwm">
          <el-button size="small" v-for="(btn,index) in btngroups.dwmbtns" :key="btn.id" @click="doSearch(index,btn.type)" :class="btngroups.dwmIndex==index?'active':''">{{btn.name}}</el-button>
        </el-button-group>

        <el-button-group class="graphType">
          <el-button size="small" v-for="(btn,index) in btngroups.graphTypebtns" :key="btn.id" @click="doSearch(index,btn.type)" :class="btngroups.graphTypeIndex==index?'active':''">{{btn.name}}</el-button>
        </el-button-group>
    </div>
    <div class="btnlist" style="margin-bottom:3px;width:100%;float:left;">
      <div style="height: 1px;clear:both;"></div>
    </div>
    <div class="report_content" style="margin-bottom:3px;width:100%;float:left;">
        <div class="chart_repot"></div>
        <div class="chart_repot_normal" :style="(!!avg.normal.normalShow?'':'display: none;')">
          <p style="font-size:12px;color:#333333;padding-left:45px;" >
            最大值: <span style="color:#e5743c; font-size:16px;" class="max">{{avg.normal.max}}</span>&nbsp;&nbsp;&nbsp;&nbsp;
            最小值: <span style="color:#e5743c; font-size:16px;" class="min">{{avg.normal.min}}</span>&nbsp;&nbsp;&nbsp;&nbsp;
            平均值: <span style="color:#e5743c; font-size:16px;" class="avg">{{avg.normal.avg}}</span>
          </p>
        </div>
        <div class="chart_repot_compare" :style="(!!avg.compare.compareShow?'':'display: none;')">
          <span style="font-size:14px;padding-left:45px;top:25px;" class="current"><span class="compareType">{{avg.compare.current.name}}</span>:&nbsp;&nbsp;&nbsp;&nbsp;
            最大值: <span style="color:#e5743c; font-size:16px;" class="max" >{{avg.compare.current.max}}</span>&nbsp;&nbsp;&nbsp;&nbsp;
            最小值: <span style="color:#e5743c; font-size:16px;" class="min">{{avg.compare.current.min}}</span>&nbsp;&nbsp;&nbsp;&nbsp;
            平均值: <span style="color:#e5743c; font-size:16px;" class="avg">{{avg.compare.current.avg}}</span>
          </span><br>
          <span style="font-size:14px;padding-left:45px;top:25px;" class="previous"><span class="compareType">{{avg.compare.previous.name}}</span>:&nbsp;&nbsp;&nbsp;&nbsp;
            最大值: <span style="color:#e5743c; font-size:16px;" class="max">{{avg.compare.previous.max}}</span>&nbsp;&nbsp;&nbsp;&nbsp;
            最小值: <span style="color:#e5743c; font-size:16px;" class="min">{{avg.compare.previous.min}}</span>&nbsp;&nbsp;&nbsp;&nbsp;
            平均值: <span style="color:#e5743c; font-size:16px;" class="avg">{{avg.compare.previous.avg}}</span>
          </span>
        </div>
    </div>
  </div>
</template>
<script>
import topoApi from 'api/topo.js'
import eventHubs from 'common/eventHubs'
import echarts from 'libs/graph/echarts.min.js'
import Utils from 'utils/filters.js'
export default {
  name: 'itemReport',
  data() {
    return {
        item:{
          itemid:'',
          valueType:-1,
          name:'',
        },
        reportData:{},
        chart:null,
        btngroups:{
          databtns:[
            {id:'data40',value:0,name:'最近40条',type:'data'},
            {id:'day1',value:1,name:'今天',type:'data'},
            {id:'day3',value:3,name:'3天',type:'data'},
            {id:'day7',value:7,name:'7天',type:'data'},
            {id:'day30',value:30,name:'30天',type:'data'}
          ],
          dataIndex:0,//选中按钮索引
          dwmbtns:[
            {id:'day',value:101,name:'日对比',current:'今天',previous:'昨天',type:'dwm'},
            {id:'week',value:102,name:'周对比',current:'本周',previous:'上周',type:'dwm'},
            {id:'month',value:103,name:'面积图',current:'本月',previous:'上月',type:'dwm'}
          ],
          dwmIndex:-1,//选中按钮索引
          graphTypebtns:[
            {id:'bar',value:1,name:'柱状图',type:'graphType'},
            {id:'line',value:2,name:'线状图',type:'graphType'},
            {id:'area',value:3,name:'面积图',type:'graphType'}
          ],
          graphTypeIndex:0,//选中按钮索引
        },
        avg:{
          normal:{
            min:0.0000,max:0.0000,avg:0.0000
          },
          normalShow:false,
          compare:{
            current:{
              name:'',min:0.0000,max:0.0000,avg:0.0000
            },
            previous:{
              name:'',min:0.0000,max:0.0000,avg:0.0000
            },
          },
          compareShow:false,
        }
    }
  },
  mounted() {
    const self = this
    this.$nextTick(function() {
      //计算统计图宽高
      let width = $('.rightLayout_topo').width()
      let height = $('.rightLayout_topo').height()
      $('.chart_repot').css({width:width?width*0.8:600,height:height?height*0.4:400})
      //统计图初始化
      self.chart = echarts.init($('.chart_repot')[0])
    })
  },
  created() {
    const self = this
    //接受item改变的事件
    eventHubs.getEventHub().$on('itemChanged', (data) => {
      self.item = data
      if(!data['reportChartData']){
        self.getData()
      }else{
        self.reportData = data.reportChartData
        self.doSearch()
      }
    });
  },
  methods: {
    doSearch(index,type){
      const self = this
      let dataIndex = 0,
          dwmIndex = -1,
          graphTypeIndex = 0
      if(type == 'data'){
          dwmIndex = -1
          dataIndex = index
          graphTypeIndex = self.btngroups.graphTypeIndex==-1?0:self.btngroups.graphTypeIndex
      }else if(type == 'dwm'){
          dataIndex = -1
          graphTypeIndex = -1
          dwmIndex = index
      }else if(type == 'graphType'){
          dwmIndex = -1
          graphTypeIndex = index
          dataIndex = self.btngroups.dataIndex==-1?0:self.btngroups.dataIndex
      }else{
          dataIndex = 0,
          dwmIndex = -1,
          graphTypeIndex = 0
      }
      if(dwmIndex > -1){
        self.avg.compare.current.name = self.btngroups.dwmbtns[dwmIndex].current
        self.avg.compare.previous.name = self.btngroups.dwmbtns[dwmIndex].previous
      }else{
        self.avg.compare.current.name = ''
        self.avg.compare.previous.name = ''
      }
      self.btngroups.dataIndex = dataIndex
      self.btngroups.dwmIndex = dwmIndex
      self.btngroups.graphTypeIndex = graphTypeIndex
      self.showCharts()
    },
    getData(){
      //获取监控项的数据
      const self = this
      if(self.item.itemid){
        topoApi.queryItemHistoryByItemId(self.item.itemid,self.item.valueType)
          .then((resp)=>{
            if(resp.data && resp.data instanceof Object && JSON.stringify(resp.data) != '{}'){
              self.reportData = resp.data
              //注册item的reportData的事件
              eventHubs.getEventHub().$emit("itemRepotChartData",{index:self.item.index, reportChartData:self.reportData});
              self.doSearch()
            }else{
              if(self.chart){
                self.chart.clear()
              }
              self.$message({message:'该项暂无报告',type:'warning'})
            }
          })
          .catch((err)=>{
            console.error(err)
            self.$message(err)
          })
      }else{
      }
    },
    showCharts(){
      const self = this
      //显示对应内容面板
      let dataIndex = self.btngroups.dataIndex,
          dwmIndex = self.btngroups.dwmIndex,
          graphTypeIndex = self.btngroups.graphTypeIndex
      if(dataIndex > -1 && graphTypeIndex > -1 && dwmIndex == -1){
          let value = self.btngroups.databtns[dataIndex].value,
              valuet = self.btngroups.graphTypebtns[graphTypeIndex].value
          //设置统计图类型
          let seriesType = '',
              itemStyle = null
          if(valuet == 1) {
              seriesType = 'bar'
              itemStyle = null
          }
          if(valuet == 2) {
              seriesType = 'line'
              itemStyle = null
          }
          if(valuet == 3) {
              seriesType = 'line'
              itemStyle = {normal: {areaStyle: {type: 'default'}}}
          }
          let repdata = []
          if(value == 0){ repdata = self.reportData.data40 } //最近40条
          if(value == 1){ repdata = self.reportData.today } //今天
          if(value == 3){ repdata = self.reportData.day3 } //3天
          if(value == 7){ repdata = self.reportData.day7 } //7天
          if(value == 30){ repdata = self.reportData.day30 } //30天
          if(repdata.length > 0){
            let temp = self.computeData(repdata)
            temp.name = self.item.name
            self.chart.clear()//清空画布，防止缓存
            self.chart.setOption(
              self.getOption(self.item.name,{type:seriesType,itemStyle:itemStyle},temp)
            )
            self.setAvgData({min:temp.min.vlaue,max:temp.max.value,avg:temp.avg})
          }
      }else if(dataIndex == -1 && graphTypeIndex == -1 && dwmIndex > -1){
          let value = self.btngroups.dwmbtns[dwmIndex].value,
              seriesType = 'bar'
          if(value == 101){//日对比
              let x = self.initArray(24).map((item,index)=>{
                return (index<10?'0'+index:index)
              })

              let y = self.initArray(24).map((item)=>{
                return item?item:0
              })
              let y2 = self.initArray(24).map((item)=>{
                return item?item:0
              })
              self.setCompareChart(self.reportData.dayCompare,seriesType,x,'点',y,y2,self.item.name,self.item.name)
          }
          if(value == 102){//周对比
              let x = ['星期日','星期一','星期二','星期三','星期四','星期五','星期六']

              let y = self.initArray(7).map((item)=>{
                return item?item:0
              })
              let y2 = self.initArray(7).map((item)=>{
                return item?item:0
              })
              self.setCompareChart(self.reportData.weekCompare,seriesType,x,'',y,y2,self.item.name,self.item.name)
          }

          if(value == 103){//月对比
              let x = self.initArray(31).map((item,index)=>{
                return index<10?'0'+(index+1):(index+1)
              })
              let y = self.initArray(31).map((item)=>{
                return item?item:0
              })
              let y2 = self.initArray(31).map((item)=>{
                return item?item:0
              })
              self.setCompareChart(self.reportData.monthCompare,seriesType,x,'号',y,y2,self.item.name,self.item.name)
          }
      }
    },
    initArray(num){
      let arr = []
      for(let i=0;i<num;i++){
        arr[i] = null
      }
      return arr
    }
    ,
    computeData(data){
      //计算横轴纵轴数据  平均值数据
      let x=[],y=[],min=0,max=0,avg=0,minx=0,miny=0,maxx=0,maxy=0
      if(data && data.length > 0){
        let avgtemp = 0
        for(let i=0;i<data.length;i++){
          x[i] = data[i].time
          try{
            y[i] = parseFloat(data[i].value)
          }catch(e){
            y[i] = 0
          }
          if(min>y[i]){
            min = y[i]
            minx = x[i]
            miny = y[i]
          }
          if(max<y[i]){
            max = y[i]
            maxx = x[i]
            maxy = y[i]
          }
          avgtemp += y[i]
        }
        avg = (avgtemp/data.length).toFixed(4)
      }
      return { x:x,y:y,min:{value:min,x:minx,y:miny},max:{value:max,x:maxx,y:maxy},avg:avg}
    },
    setAvgData(v,v2){
      const self = this
      //设置平均值 最大值  最小值 在统计图的下面显示
      if(self.btngroups.dwmIndex == -1){
        self.avg.normal.normalShow = true
        self.avg.compare.compareShow = false
        self.avg.normal.min = v.min&&v.min!=0?v.min:'0.0000'
        self.avg.normal.max = v.max&&v.max!=0?v.max:'0.0000'
        self.avg.normal.avg = v.avg&&v.avg!=0?v.avg:'0.0000'
      }else{
        self.avg.normal.normalShow = false
        self.avg.compare.compareShow = true
        self.avg.compare.current.min = v.min&&v.min!=0?v.min:'0.0000'
        self.avg.compare.current.max = v.max&&v.max!=0?v.max:'0.0000'
        self.avg.compare.current.avg = v.avg&&v.avg!=0?v.avg:'0.0000'
        self.avg.compare.previous.min = v2.min&&v.min!=0?v2.min:'0.0000'
        self.avg.compare.previous.max = v2.max&&v2.max!=0?v2.max:'0.0000'
        self.avg.compare.previous.avg = v2.avg&&v2.avg!=0?v2.avg:'0.0000'
      }
    },
    getOption(title,series,xy,xy2){
      //获取统计图的绘图选项
      const self = this
      let seriesData = [{
            name:xy.name,
            type:series.type,
            itemStyle:series.itemStyle,
            data:xy.y,
            markPoint :{},
            markLine : {}
        }
      ]
      if(xy2){
        seriesData.push({
            name:xy2.name,
            type:series.type,
            itemStyle:series.itemStyle,
            data:xy2.y
        })
      }else{
        let markPoint =   {
                  data : [
                      {name : '最大值', value : xy.max.value, xAxis: xy.max.x, yAxis: xy.max.y},
                      {name : '最小值', value : xy.min.value, xAxis: xy.min.x, yAxis: xy.min.y, symbolSize:30}
                  ]
              }
        let markLine =  {
                  data : [
                      {type : 'average', name : '平均值'}
                  ]
              }
        seriesData[0].markPoint = {}//markPoint
        seriesData[0].markLine = markLine
      }
      return {
          title : {
              text: self.item.name
          },
          tooltip : {
              trigger: 'axis'
          },
          calculable : true,
          xAxis : [
              {
                  type : 'category',
                  data : xy.x,
                  axisLabel:{
                    formatter:function(value){
                       if(/^\d+$/.test(value)){
                         value = parseInt(value)
                       }else if(/^\d+\.{0,1}\d+$/.test(value)){
                         value = parseFloat(value)
                       }
                      return value+(xy.units?xy.units:'')
                    }
                  }
              }
          ],
          yAxis : [
              {
                  type : 'value'
              }
          ],
          series : seriesData
      }
    },
    //设置比较的统计图
    setCompareChart(data,seriesType,x,xunits,y,y2,namey,namey2){
      const self = this
      let compare = data,
          current = compare.data,
          avg = compare.avg,
          previous = compare.data_o,
          avg_o = compare.avg_o
        for(let i=0;i<x.length;i++){
            for(let item of current){
                if(item.time == x[i]){
                  y[i] = item.value?item.value:0
                  break
                }
            }
            for(let item of previous){
                if(item.time == x[i]){
                  y2[i] = item.value?item.value:0
                  break
                }
            }
        }
        let option = self.getOption(self.item.name,{type:seriesType,itemStyle:null}, {x:x,units:xunits,y:y,name:'('+self.avg.compare.current.name+')'+namey}, {x:x,y:y2,name:'('+self.avg.compare.previous.name+')'+namey2})
      self.chart.clear()//清空画布，防止缓存
      self.chart.setOption(option )
      self.setAvgData({min:avg.min,max:avg.max,avg:avg.avg},{min:avg_o.min,max:avg_o.max,avg:avg_o.avg})
    },
  }
}
</script>
<style scoped>
.el_btn_report .active {
  color: #1d90e6;
  border-color: #1d90e6;
  outline: 0;
}
</style>
